<template>
	<view id="switchAccounts">
		<mescroll-body ref="mescrollRef" :sticky="true" :down="{ native: true }" @init="mescrollInit" @down="downCallback" :up="upOption"  @up="upCallback">
			<view>
				<view class="accounts-list" @click="chooseAccount(item)" v-for="(item,index) in accountList" :key="index">
					<view class="accounts-left">
						<!-- <image class="image" src="/static/empty.png" mode="scaleToFill"></image> -->
						<avatar-image :url="item.avatar_url" :width="100" />
						<view class="accounts-content">
							<view class="nickname">{{item.nick_name}}</view>
							<view class="mobile">{{item.mobile}}</view>
						</view>
					</view>
					<view class="accounts-right" v-if="isActive == item.user_id"><uni-icons type="checkmarkempty" size="18" color="#fa2209"></uni-icons></view>
				</view>
			</view>
		</mescroll-body>
	</view>
</template>

<script>
	import MescrollMixin from '@/uni_modules/mescroll-uni/components/mescroll-uni/mescroll-mixins'
	import * as UserApi from '@/api/user'
	import AvatarImage from '@/components/avatar-image'
	import storage from '@/utils/storage'
	import { ACCESS_TOKEN, USER_ID } from '@/store/mutation-types'
	import store from '@/store'
	export default {
	  mixins: [MescrollMixin],
	  components: {
		  AvatarImage
	  },
	  data() {
	    return {
			accountList: [], // 关联账户
			isActive: '',
			upOption: {
			  // 首次自动执行
			  auto: true,
			  // 每页数据的数量; 默认10
			  page: { size: 10 },
			  // 数量要大于4条才显示无更多数据
			  noMoreSize: 4,
			  // 空布局
			  empty: {
			    tip: '亲，暂无关联账户'
			  }
			},
		}
	  },
	  
	  /**
	   * 生命周期函数--监听页面显示
	   */
	  onLoad(options) {},
	  
	  /**
	   * 生命周期函数--监听页面显示
	   */
	  onShow(options) {
		  const app = this
		  
	  },
	  methods: {
		  /**
		   * 上拉加载的回调 (页面初始化时也会执行一次)
		   * 其中page.num:当前页 从1开始, page.size:每页数据条数,默认10
		   * @param {Object} page
		   */
		  upCallback(page) {
		    console.log(page)
		    const app = this
		    // 设置列表数据
		    app.getAccount().then(result => {
			   console.log('result33',result)
			   app.accountList = result.data
			   const curPageLen = result.data.length
			   const totalSize = result.data.length
			   app.mescroll.endBySize(curPageLen, totalSize)
		    })
		    .catch(err => {
				console.log('catch', err)
				app.mescroll.endErr()
			})
		    .finally(() => app.isLoading = false)
		  },
		  // 获取关联的账号列表
		  getAccount() {
		    const app = this
		    return new Promise((resolve, reject) => {
		      UserApi.getAccountList({}, { load: true })
		        .then(result => {
				  console.log('result',result)
		          resolve(result)
		        })
		        .catch(err => {
		          if (err.result && err.result.status == 401) {
		            resolve(null)
		          } else {
		            reject(err)
		          }
		        })
		    })
		  },
		  // 选择账户
		  chooseAccount(val) {
			  const app = this
			  UserApi.switchAccountLogin({ account: val.user_id})
			    .then(result => {
			      // 显示操作成功
			      app.$toast(result.message)
				  app.isActive = val.user_id
				  // 过期时间30天
				  const expiryTime = 30 * 86400
				  // 保存tokne和userId到缓存
				  storage.set(USER_ID, result.data.userId, expiryTime)
				  storage.set(ACCESS_TOKEN, result.data.token, expiryTime)
				  // 用户认证token
				  store.commit('SET_TOKEN', result.data.token)
				  // 当前用户ID
				  store.commit('SET_USER_ID', result.data.userId)
			      // 跳转回原页面
			      setTimeout(() => {
			        app.onNavigateBack(1)
			      }, 2000)
			    })
			    .finally(() => app.isLoading = false)
		  },
		  /**
		   * 提交成功-跳转回原页面
		   */
		  onNavigateBack(delta) {
			uni.$emit('refreshData',{refresh: true});
		    uni.navigateBack({
		      delta: Number(delta || 1)
		    })
		  }
	  }
	}
</script>

<style scoped lang="scss">
	#switchAccounts{
		background-color: #fff;
		
	}
	.accounts-list{
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding:14rpx 24rpx;
		border-bottom: 1rpx solid #eee;
		.image{
			width: 80rpx;
			height: 80rpx;
			border-radius: 50%;
		}
		.accounts-left{
			display: flex;
			align-items: center;
			.accounts-content{
				margin-left: 35rpx;
				line-height: 35rpx;
			}
			.mobile{
				font-size: 22rpx;
			}
		}
	}
</style>